using System;
using Godot;

public partial class MoveCommand : Node3D
{
	public static MoveCommand Instance;
	public struct Target
	{
		public Vector3 position;
		public Unit unit;
	}
	public Target? target = null;
	public Action<Target> onPick = null;

	public override void _Ready()
	{
		SetProcessInput(true);
		Instance = this;
	}

	public override void _Process(double delta)
	{
		if (Input.IsActionJustPressed("MoveCommand"))
		{
			target = CaptureObjectUnderMouse();
			if (target != null)
			{
				onPick?.Invoke(target.Value);
				return;
			}

		}
	}

	private Target? CaptureObjectUnderMouse()
	{
		// 获取鼠标位置
		Vector2 mousePosition = GetViewport().GetMousePosition();
		// 创建射线查询参数
		var from = GetViewport().GetCamera3D().ProjectRayOrigin(mousePosition);
		var to = from + GetViewport().GetCamera3D().ProjectRayNormal(mousePosition) * 1000; // 射线长度可以根据需要调整


		// 执行射线查询
		var spaceState = GetWorld3D().DirectSpaceState;
		var query = PhysicsRayQueryParameters3D.Create(from, to);
		var result = spaceState.IntersectRay(query);

		if (result.Count > 0)
		{
			var colider = result["collider"].As<Node3D>();
			if (colider != null)
			{
				return new Target(){
					position = result["position"].As<Vector3>(),
					unit = colider as Unit
				};
			}
		}
		return null;
	}
}
